package ruifeng.zcj.communcationring.base;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Vibrator;
import android.support.multidex.MultiDex;

import com.baidu.mapapi.SDKInitializer;
import com.easemob.easeui.controller.EaseUI;
import com.lidroid.xutils.HttpUtils;
import com.se7en.utils.SystemUtil;

import java.util.Iterator;
import java.util.List;

import huanxin.DemoHelper;
import ruifeng.zcj.communcationring.base.api.ApiHttpClient;
import ruifeng.zcj.communcationring.groble.utils.CrashHandler;
import ruifeng.zcj.communcationring.ui.LocationService;


/**
 * 内存泄漏处理
 * https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
 * http://jiagu.360.cn/qcmshtml/manager.html#crash
 * apk加固
 * http://jiagu.360.cn/qcmshtml/manager.html#record
 * Created by baixiaokang on 16/4/23.
 */
public class App extends Application {
    private static App mApp;
    private static int mainThreadId;
    private static Handler handler;
    public static String cacheDir = "";
    // EMOptions options = new EMOptions();

    public LocationService locationService;
    public Vibrator mVibrator;


    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        mainThreadId = android.os.Process.myTid();// 获取当前主线程id
        handler = new Handler();
        SystemUtil.setContext(this);

        Local();
        // LOG日志
        //Logger.init().logLevel(LogLevel.FULL);
        //LeakCanary检测OOM  oom出的原因就是内存泄漏
       // LeakCanary.install(this);
        //初始化日志输出工具
        CrashHandler.init(new CrashHandler(getApplicationContext()));
        /**
         * 如果存在SD卡则将缓存写入SD卡,否则写入手机内存
         */
        if (getApplicationContext().getExternalCacheDir() != null && isExistSDCard()) {
            cacheDir = getApplicationContext().getExternalCacheDir().toString();
        } else {
            cacheDir = getApplicationContext().getCacheDir().toString();
        }

        EaseUI.getInstance().init(this);
        //init demo helper 设置后台监听事件，视频，语音啥的
        DemoHelper.getInstance().init(getInstance());


      /*  // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        //自动登录
        options.setAutoLogin(true);
        // 如果APP启用了远程的service，此application:onCreate会被调用2次
        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
        // 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回
        init();
        //初始化
        EMClient.getInstance().init(this, options);*/
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
       // EMClient.getInstance().setDebugMode(true);


        initHttp();
    }
    private void initHttp() {
        // 初始化网络请求
        HttpUtils client = new HttpUtils();
        ApiHttpClient.setHttpClient(client);

    }


    /***
     * 定位
     * **/
    private void Local() {
        locationService = new LocationService(getApplicationContext());
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());

    }

    private boolean isExistSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private void init() {
        String processAppName = getAppName(mainThreadId);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回
        if (processAppName == null || !processAppName.equalsIgnoreCase(this.getPackageName())) {
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    public static Context getAppContext() {
        return mApp;
    }

    public static Resources getAppResources() {
        return mApp.getResources();
    }

    public static int getMainThreadId() {
        return mainThreadId;
    }

    public static Handler getHandler() {
        return handler;
    }


    /**
     * 获得当前app运行的AppContext
     *
     * @return
     */
    public static App getInstance() {
        return mApp;
    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
